package common

import security.Role

/**
 * InitializeRolesService
 * A service class encapsulates the core business logic of a Grails application
 */
class SecurityService {
	public final String ADMIN_ROLE = "ADMIN_ROLE"
	public final String STUDENT_ROLE = "STUDENT_ROLE"
	public final String PROFESSOR_ROLE = "PROFESSOR_ROLE"
	 
    static transactional = true

    def createRoles() {
		def studentRole = Role.findByName(STUDENT_ROLE)
		if (!studentRole) {
			studentRole = new Role(name: STUDENT_ROLE)
			studentRole.addToPermissions("student:show,listEnroledCourses,createInscriptionToCourse")
			studentRole.addToPermissions("department:list,show")
			studentRole.addToPermissions("major:list,show")
			studentRole.addToPermissions("course:list,show")
			studentRole.addToPermissions("subject:list,show")
			studentRole.addToPermissions("inscriptionCourse:list,show,create")
		}
		
		def professorRole = Role.findByName(PROFESSOR_ROLE)
		if (!professorRole) {
			professorRole = new Role(name: PROFESSOR_ROLE)
			professorRole.addToPermissions("department:list,show")
			professorRole.addToPermissions("major:list,show")
			professorRole.addToPermissions("course:list,show,create")
			professorRole.addToPermissions("subject:list,show")
			professorRole.addToPermissions("inscriptionCourse:list,show")
			professorRole.addToPermissions("inscriptionMajor:list,show")
		}
		
		def adminRole = Role.findByName(ADMIN_ROLE)
		if (!adminRole) {
			adminRole = new Role(name: ADMIN_ROLE)
			adminRole.addToPermissions("*:*")
		}
		
		studentRole.save(flush: true, failOnError: true)
		professorRole.save(flush: true, failOnError: true)
		adminRole.save(flush: true, failOnError: true)
    }
}
